#!/bin/bash

set -e
# set -x

startTime=$(date +%s)

current_path=$(cd `dirname $0`; pwd)

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

if command -v nvm > /dev/null 2>&1; then
    NVM_NODEJS_ORG_MIRROR=http://npm.taobao.org/mirrors/node nvm install 12.16.1
fi

# OSS 上传的目录，每个项目不一样
if [ -z $ossPath ];then
    ossPath=cloudpivot
fi

if [ -z "$ossDomain" ];then
    # dev-venus-pub.oss-cn-beijing.aliyuncs.com
    ossDomain=//cdn.wzw.cn
fi

echo "ossDomain: $ossDomain"

rm -rf Always-*.html dist build archiveFile

if [ -f yarn.lock ];then
    yarn install --frozen-lockfile --ignore-optional
else
    npm install --no-optional
fi

rm -rf ../dist ../node_modules ../entries/admin/node_modules ../entries/portal/node_modules ../entries/mobile/node_modules

cd "$current_path"

npm run installs
rm -rf ./dist && mkdir ./dist

datestr=$(date "+%Y-%m-%d %H:%M:%S")
# 注入版本信息，便于排查当前版本信息
echo "<title>cloudpivot-web $datestr</title><meta name=version content=$BUILD_NUMBER-$GIT_COMMIT>" > ./dist/index.html
cd $current_path/entries/admin && NODE_ENV=production PUBLIC_PATH=$ossDomain/cloudpivot/admin/ npm run build && mv ./dist ../../dist/admin && cd ../../
cd $current_path/entries/portal && NODE_ENV=production PUBLIC_PATH=$ossDomain/cloudpivot/portal/ npm run build && mv ./dist ../../dist/portal && cd ../../
cd $current_path/entries/mobile && NODE_ENV=production PUBLIC_PATH=$ossDomain/cloudpivot/mobile/ npm run build && mv ./dist ../../dist/mobile && cd ../../

endTime=$(date +%s)
during=$((endTime - startTime))
echo "[build time]: $during s, (not include oss upload)"
